<template>
  <base-layout>
    <!-- 搜索区域 -->
    <div class="search-card">
      <div class="search-area">
        <a-input-search
          v-model:value="searchText"
          placeholder="项目名称/所属课程"
          class="search-input"
          @search="onSearch"
          allow-clear
        >
          <template #prefix>
            <search-outlined />
          </template>
        </a-input-search>

        <div class="filter-area">
          <a-radio-group v-model:value="type" button-style="solid" @change="onFilterChange">
            <a-radio-button value="all">全部</a-radio-button>
            <a-radio-button value="course">课程项目</a-radio-button>
            <a-radio-button value="comprehensive">综合项目</a-radio-button>
          </a-radio-group>
        </div>
      </div>
    </div>

    <!-- 项目列表 -->
    <a-card class="table-card">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="onTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="handleStart(record)">开始实践</a-button>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ record.status }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'points'">
            <span :style="{ color: '#52c41a', fontWeight: 'bold' }">
              +{{ record.points }}
            </span>
          </template>
        </template>
      </a-table>
    </a-card>
  </base-layout>
</template>

<script>
import BaseLayout from '@/components/layout/BaseLayout.vue'
import {
  HomeOutlined,
  CodeOutlined,
  ProjectOutlined,
  ReadOutlined,
  TrophyOutlined,
  SettingOutlined,
  BarChartOutlined,
  SearchOutlined,
  BellOutlined,
  UserOutlined,
  LogoutOutlined,
  CalendarOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  PlusOutlined,
} from '@ant-design/icons-vue'
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { getUnreadCount } from '@/api/notification'
import { getCheckInStatus, checkIn } from '@/api/oj'
import { getProjects, deleteProject } from '@/api/projects.js'

export default {
  name: 'Project',
  components: {
    BaseLayout,
    HomeOutlined,
    CodeOutlined,
    ProjectOutlined,
    ReadOutlined,
    TrophyOutlined,
    SettingOutlined,
    BarChartOutlined,
    SearchOutlined,
    BellOutlined,
    UserOutlined,
    LogoutOutlined,
    CalendarOutlined,
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    PlusOutlined,
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const currentRoute = ref(route.name.toLowerCase())
    const searchText = ref('')
    const type = ref('all')
    const loading = ref(false)
    const tableData = ref([])
    const pagination = ref({
      current: 1,
      pageSize: 10,
      total: 0,
      showTotal: (total) => `共 ${total} 条`
    })
    const checkInLoading = ref(false)
    const isCheckedIn = ref(false)
    const unreadCount = ref(0)

    const columns = [
      {
        title: '编号1',
        dataIndex: 'id',
        key: 'id',
        width: 100,
      },
      {
        title: '项目名称',
        dataIndex: 'name',
        key: 'name',
        ellipsis: true,
      },
      {
        title: '所属课程',
        dataIndex: 'course',
        key: 'course',
        width: 200,
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 120,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 180,
      },
      {
        title: '完成时间',
        dataIndex: 'finishTime',
        key: 'finishTime',
        width: 180,
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 120,
      },
      {
        title: '分数',
        dataIndex: 'score',
        key: 'score',
        width: 100,
      },
      {
        title: '积分',
        dataIndex: 'points',
        key: 'points',
        width: 100,
      },
      {
        title: '操作',
        key: 'action',
        width: 120,
        fixed: 'right'
      }
    ]

    // 模拟项目数据
    const allProjects = [
      {
        id: 1,
        name: '面向对象程序设计项目',
        course: '面向对象程序设计（Java）',
        type: '课程项目',
        createTime: '2024-10-10 10:10:10',
        finishTime: '-',
        status: '系统设计待批阅',
        score: '-',
        points: 0
      },
      {
        id: 2,
        name: 'Web全栈开发项目',
        course: 'Web应用开发',
        type: '课程项目',
        createTime: '2024-10-10 10:10:10',
        finishTime: '2024-10-10 10:10:10',
        status: '已完成',
        score: '100',
        points: 30
      },
      {
        id: 3,
        name: '校园二手交易平台',
        course: '-',
        type: '综合项目',
        createTime: '2024-10-10 10:10:10',
        finishTime: '-',
        status: '创建项目',
        score: '-',
        points: 0
      },
      {
        id: 4,
        name: '智能问答系统',
        course: '-',
        type: '综合项目',
        createTime: '2024-10-10 10:10:10',
        finishTime: '2024-10-10 10:10:10',
        status: '已完成',
        score: '98',
        points: 40
      }
    ]

    // 获取项目列表
    const fetchProjects = () => {
      loading.value = true
      getProjects().then(res => {
        let filteredData = [...res.content]//拷贝接口返回的数据    [...res] 拷贝res的值,避免直接操作原数据
        tableData.value = filteredData//更新表格数据
        pagination.value.total = filteredData.length
        loading.value = false
      })
    }

    // 搜索处理
    const onSearch = (value) => {
      searchText.value = value
      pagination.value.current = 1
      
      // 如果搜索框为空，则获取所有项目
      if (!value.trim()) {
        fetchProjects()
        return
      }
      
      // 调用接口并根据课程名称筛选
      loading.value = true
      getAssignments().then(res => {
        const searchLower = value.toLowerCase()
        // 筛选包含搜索关键词的项目（项目名称或所属课程）
        let filteredData = [...res].filter(item => 
          (item.name && item.name.toLowerCase().includes(searchLower)) || 
          (item.course && item.course.toLowerCase().includes(searchLower))
        )
        
        tableData.value = filteredData
        pagination.value.total = filteredData.length
        loading.value = false
        
        if (filteredData.length === 0) {
          message.info('未找到相关课程或项目')
        }
      }).catch(error => {
        message.error('搜索失败')
        console.error('搜索失败:', error)
        loading.value = false
      })
    }

    // 筛选变化处理
    const onFilterChange = () => {
      pagination.value.current = 1
      fetchProjects()
    }

    // 表格分页变化处理
    const onTableChange = (pag) => {
      pagination.value.current = pag.current
      fetchProjects()
    }

    const handleStart = (record) => {
      router.push(`/project/problem/${record.id}`)
    }

    const handleDelete = async (record) => {
      try {
        await deleteAssignment(record.id)
        message.success('删除成功')
        fetchProjects()
      } catch (error) {
        message.error('删除失败')
      }
    }

    const getStatusColor = (status) => {
      const colors = {
        '已完成': 'success',
        '系统设计待批阅': 'processing',
        '创建项目': 'default'
      }
      return colors[status] || 'default'
    }

    // 获取签到状态
    const fetchCheckInStatus = async () => {
      // try {
      //   const res = await getCheckInStatus()
      //   isCheckedIn.value = res.data.isCheckedIn
      // } catch (error) {
      //   message.error('获取签到状态失败')
      // }
    }

    // 签到
    const handleCheckIn = async () => {
      if (isCheckedIn.value) {
        message.info('今日已签到')
        return
      }

      checkInLoading.value = true
      try {
        await checkIn()
        message.success('签到成功')
        isCheckedIn.value = true
      } catch (error) {
        message.error('签到失败')
      } finally {
        checkInLoading.value = false
      }
    }

    // 获取未读消息数量
    const fetchUnreadCount = async () => {
      try {
        const res = await getUnreadCount()
        unreadCount.value = res.data
      } catch (error) {
        console.error('获取未读消息数量失败')
      }
    }

    const handleLogout = () => {
      localStorage.removeItem('token')
      router.push('/')
    }

    // 页面加载时获取数据
    onMounted(() => {
      fetchProjects()
      fetchCheckInStatus()
      fetchUnreadCount()
    })

    return {
      currentRoute,
      searchText,
      type,
      loading,
      tableData,
      columns,
      pagination,
      onSearch,
      onFilterChange,
      onTableChange,
      handleStart,
      handleDelete,
      getStatusColor,
      checkInLoading,
      isCheckedIn,
      unreadCount,
      handleCheckIn,
      handleLogout,
    }
  }
}
</script>

<style scoped>
.search-card {
  background: white;
  padding: 24px;
  margin-bottom: 16px;
  border-radius: 12px;
  box-shadow: var(--shadow-1);
}

.search-area {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.filter-area {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-card {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: var(--shadow-1);
  overflow-x: auto;
}

:deep(.ant-table-wrapper) {
  width: 100%;
}

:deep(.ant-table) {
  overflow-x: auto;
}

:deep(.ant-table-content) {
  overflow-x: auto;
}

:deep(.ant-table-body) {
  overflow-x: auto !important;
}

@media screen and (max-width: 768px) {
  .search-area {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    width: 100%;
  }

  .filter-area {
    justify-content: flex-start;
    overflow-x: auto;
  }
}
</style> 